<?php
namespace wlcat\src;
abstract class Config {
    static $config;
    //根据config文件，初始化配置
    public static function init()
    {
        if (empty(self::$config))
        {
            //初始化config的值
            $basePath = APP_PATH.APPLICATION_NAME."/config/";
            $config['config'] = include_once $basePath."config.php";
            if (isset($config['config']['config_path']))
            {
                foreach ($config['config']['config_path'] as $c)
                {
                    $filePath = $basePath.$c;
                    if (file_exists($filePath))
                    {
                        $k = str_replace('.php', '', $c);
                        $config[$k] =  include_once $filePath;
                    }
                }
            }
            self::$config = $config;
        }
    }

    /**获取配置
     * @param $key  '文件名.键名.键名'
     * @return mixed
     */
    public static function get($key) {
        return self::getArrValBykeys(self::$config, explode('.', $key));
    }

    /**设置配置
     * @param $key '文件名.键名.键名'
     * @param $value 对应的值
     */
    public static function set($key, $value)
    {
        $keys = explode('.', $key);
        //设置config
        $temp = &self::$config;
        foreach ($keys as $index => $key)
        {
            //循环最后一个 赋值
            if (count($keys) == $index + 1)
            {
                $temp[$key] = $value;
            }
            elseif (is_array($temp) && array_key_exists($key, $temp))
            {
                //按引用传递
                $temp = &$temp[$key];
            }
        }
    }

    private static function getArrValBykeys($arr, $keys)
    {
        if (count($keys) > 1) {
            $keys1 = $keys;
            foreach ($keys as $index => $key) {
                if (array_key_exists($key, $arr)) {
                    unset($keys1[$index]);
                    //递归获取值
                    return self::getArrValBykeys($arr[$key], $keys1);
                }
            }
        } else {
            $key = array_values($keys)[0];
            return array_key_exists($key, $arr) ? $arr[$key] : null;
        }

    }
}